package com.atguigu.gmall.product.controller;

import com.alibaba.cloud.sentinel.SentinelProperties;
import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.java.Log;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Author: zm
 * @Date: 2021/8/8 21:09
 */
@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secreKey}")
    private String secreKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    // http://api.gmall.com/admin/product/fileUpload
    // 文件上传
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception {
        String url ="";
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        // MinioClient minioClient = new MinioClient("https://play.min.io", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
        MinioClient minioClient  = MinioClient.builder()
                .endpoint(endpointUrl)
                .credentials(accessKey, secreKey)
                .build();

        // 检查存储桶是否已经存在
        boolean isExist  = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(isExist ){
            System.out.println("Bucket already exists.");
        }else {
            // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        }

        //  定义一个文件的名称 : 文件上传的时候，名称不能重复！
        String extName = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = System.currentTimeMillis()+ UUID.randomUUID().toString()+"."+extName;

        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                        file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())// 不知道文件的类型也可以回显 加不加都可以
                        .build());

        //  回显：图片的全路径！
        //  http://39.99.159.121:9000/gmall/xxxxx;
        url = endpointUrl+"/"+bucketName+"/"+fileName;
        System.out.println("url:\t"+url);
        return Result.ok(url);
    }



}


